from google.appengine.api import memcache
from google.appengine.ext import db
from logger.models import SettingsEntry

class Settings(object):

    def init(self, name, val):
        data = SettingsEntry.all().filter('skey =',name).get()
        if data is None:
            self.set(name, val)

    def get(self, name):
        data = memcache.get("settings_"+name)
        if data is not None:
            return data
        else:
            data = SettingsEntry.all().filter('skey =',name).get()
            if data is None:
                raise db.BadPropertyError
            memcache.add("settings_"+name, data.sval)
            return data.sval

    def set(self, name, val):
        entry = SettingsEntry.all().filter('skey =',name).get()
        if entry is None:
            entry = SettingsEntry(skey=name, sval=val)
            entry.put()
        else:
            entry.sval = val
            entry.put()
        memcache.delete("settings_"+name)

    def getall(self):
        return SettingsEntry.all().fetch(1000)



SETTINGS = Settings()
SETTINGS.init('jid_sender', 'alert@examplelog.appspotchat.com')
SETTINGS.init('email_sender', 'example@gmail.com')
